use std::fs;

use bindgen::Builder;
use cc::Build;


pub const C_SRC_PATH: &'static str = "./c_src/";

fn find_src_file() -> Vec<String> {
    let mut vec = Vec::new();
    let mut dir = fs::read_dir(C_SRC_PATH).unwrap();

    while let Some(Ok(file)) = dir.next() {
        if !file.file_type().unwrap().is_file() {
            continue;
        }
        let name = file.file_name();
        let name = name.to_str().unwrap();
        if !name.ends_with(".c") {
            continue;
        }
        vec.push(file.path().to_str().unwrap().to_string());
    }
    vec
}

fn build_c() {
    let mut build = Build::new();
    build.define("STM32F10X_MD", "");
    build.include("./c_src/CMSIS");
    let srcs = find_src_file();
    for src in srcs {
        build.file(src);
    }
    build.try_compile("test").unwrap();
}

fn bind_head() {
    let builder = Builder::default()
    .header("./c_src/test.h")
    .header("./c_src/system_stm32f10x.h")
    .use_core()
    .generate().unwrap();

    builder.write_to_file("./test.rs").unwrap();
}

fn main() {
    println!("cargo:rerun-if-changed=build.rs");

    println!("cargo:warning={} {}", "build", env!("CC"));

    let c_src = find_src_file();
    println!("cargo:warning={} {:?}", c_src.len(), c_src);

    build_c();
    bind_head();
}


